<template>
  <div>
    <!-- 上传 -->
    <el-upload class="upload-demo" action="#"
      :http-request="({ file, onProgress, onSuccess, onError }) => fileUpload(file, onProgress, onSuccess, onError, item)"
      :accept="item.accept || fileAccept" :on-success="handleSuccess" :file-list="fileList" :show-file-list="false"
      :before-upload="(file) => beforeUpload(file, item)" multiple :limit="item.limit" :on-exceed="handleExceed"
      :on-progress="handleProgress">
      <el-button size="small" type="primary" :disabled="item.disabled">点击上传<i
          class="el-icon-upload el-icon--right"></i></el-button>
      <div slot="tip" class="el-upload__tip">只能上传{{ item.accept.split(',').join('、') }}等格式文件</div>
    </el-upload>
    <!-- 自定义文件列表 -->
    <div class="file-list">
      <div class="file-items" v-for="(file, index) in fileList" :key="index">
        <!-- {{ file }} -->
        <div class="file-icon"><i class="el-icon-tickets"></i></div>
        <div class="file-con">
          <div class="file-name line-1">{{ file.name }}</div>
          <el-progress type="line" v-if="file.percentage !== 100" class="file-progress" :show-text="false"
            :stroke-width="2" :percentage="file.percentage">
          </el-progress>
        </div>
        <div class="file-status" v-if="file.status == 'success' && file.percentage == 100"><i
            class="el-icon-circle-check" :style="{ color: '#67C23A', fontSize: '18px' }"></i></div>
        <div class="file-status" v-else-if="file.status == 'error'"><i class="el-icon-circle-close"
            :style="{ color: '#F56C6C', fontSize: '18px' }"></i></div>
        <div class="file-status" v-else></div>
        <div>
          <el-button size="mini" type="danger" @click="fileRemove(file, index)" :disabled="item.disabled">删除</el-button>
          <el-button size="mini" @click="fileView(file, index)">预览</el-button>
          <el-button size="mini" type="primary" @click="fileDownLoad(file)">下载</el-button>
        </div>
      </div>
    </div>
    <filePreview :isShowFilePreview="isShowFilePreview" :fileData="fileData" @handleClose="closeFileView"></filePreview>
  </div>

</template>

<script>
import { uploadFile, uploadRemove } from "@/api/upload/upload";
import { downloadFile,fileViewApi } from '@/api/download/index'
import { downloadLinkFile } from '@/utils/common'
import filePreview from "@/components/filePreview/filePreview.vue";
export default {
  components:{
    filePreview
  },
  props: {
    item: {
      type: Object,
      default: () => { }
    },
    defaultFileList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    defaultFileList: {
      handler(newValue, oldValue) {
        this.fileList = this.defaultFileList;
      },
      immediate: true,
      deep: true
    },
  },
  data() {
    return {
      fileList: [],
      fileData:{},
      isShowFilePreview:false,
      fileAccept: '.xls,.xlsx',
      isFileUploadLoading: false
    }
  },
  methods: {
    // 上传文件校验
    beforeUpload(file, item) {
      let fileAccept, fileExtension, isAcceptFile;
      item.fileMaxSize = item.fileMaxSize || 15;
      fileAccept = item.accept || this.fileAccept;
      if (typeof fileAccept == 'string') {
        fileAccept = fileAccept.split(',');
        fileExtension = file.name.substring(file.name.lastIndexOf('.'));
      }
      if (Array.isArray(fileAccept)) {
        isAcceptFile = fileAccept.includes(fileExtension);
      }
      const isTrueSize = file.size / 1024 / 1024 < item.fileMaxSize;
      if (!isAcceptFile) {
        this.$message.error(`上传只能是 ${item.accept}格式!`);
      }
      if (!isTrueSize) {
        this.$message.error(`上传大小不能超过 ${item.fileMaxSize}MB!`);
      }
      return isAcceptFile && isTrueSize;
    },
    fileUpload(file, onProgress, onSuccess, onError, item) {
      this.isFileUploadLoading = true;
      this.uploadFile(file, item, onProgress).then(res => {

        if (res && res.code == 200 && res.data) {
          onSuccess({ res, item })
          this.isFileUploadLoading = false;
        }
      }).catch(err => {
        onError(err)
        this.isFileUploadLoading = false;
      })
    },
    handleSuccess({ res, item }, file) {
      this.fileList.push({
        name: res.data.originName,
        uid: file.uid,
        url: res.data.url,
        status: file.status,
        percentage: file.percentage
      });
      this.$emit('dataFile', this.copyFileList(this.fileList))
    },
    uploadFile(file, item, onProgress) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", item.uploadType);
      return uploadFile(formData, progressEvent => {
        onProgress({ percent: progressEvent })
      }).then((res) => {
        return res;
      });
    },
    fileRemove(file, index) {
      this.fileList.splice(index, 1)
      this.$nextTick(()=>{
        this.$emit('dataFile', this.copyFileList(this.fileList))
      })
    },
    copyFileList(list=[]){
      let arr = list.map(item => {
        return {
          name: item.name,
          url: item.url
        }
      })
      return arr.length == 0 ? "" : JSON.stringify(arr)
    },
    fileView(file, index) {
      if(!file.url) return false;
      let suffix = file.url.split('.')[1];
      
      fileViewApi({
        url: file.url
      }).then(res => {
        if (res.code == 200) {
          this.isShowFilePreview = true;
          this.fileData = Object.assign({},{
            suffix,
            fileUrl:res.data.url
          })
        }
      })
      
      // console.log(file,'viewFile',suffix,this.fileData)
    },
    closeFileView(){
      this.isShowFilePreview = false;
      this.fileData = Object.assign({},{})
    },
    fileDownLoad(file, fileList) {
      downloadFile({
        url: file.url
      }).then(res => {
        if (res.code == 200) {
          downloadLinkFile(res.data.url, file.name)
        }
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 50 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleProgress(event, file, fileList) {
      // 更新文件的上传进度

      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].url === file.url) {
          this.fileList[i]['percentage'] = event.percent; // 假设event.percent是上传进度百分比
          break;
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.upload-file-list .upload-file-item {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-file-list .file-name,
.upload-file-list .file-size {
  margin-right: 10px;
}

.file-list {
  height: 250px;
  overflow-y: scroll;
}

.file-items {
  display: grid;
  grid-template-columns: 20px 200px 20px 1fr;
  width: 100%;
  font-size: 12px;
  height: 40px;
  align-items: center;
  grid-gap: 20px 10px;

  .file-con {
    position: relative;
    height: 100%;

    .file-name {
      // padding-bottom: 25px;
      box-sizing: border-box;
      line-height: 40px;
    }

    .file-progress {
      top: 35px;
    }
  }
}
</style>
